package com.Shiro;

import com.Pojo.User;
import com.Utils.RedisUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * Created by XingYang on 2019/3/5.
 */

public class UserRealm extends AuthorizingRealm  {

    //获取redis连接
    Jedis jedis = new RedisUtil().getClient();
    Logger log =  Logger.getLogger(UserRealm.class);



    @Override
    public String getName() {
        return "UserRealm";
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        User user = null;
        String username = (String)authenticationToken.getPrincipal();
        //若缓存中不存在该用户信息
        if(jedis.llen(username.getBytes())==0){
             throw  new UnknownAccountException();
        }
        user = (User)new RedisUtil().unSerializseObj(jedis.lrange(username.getBytes(),0,0).get(0));
        String pwd = (String)user.getPassword();
        if(!"1".equals(user.getEffect())){
            //用户状态为锁定
            throw new LockedAccountException();
        }

        AuthenticationInfo authc = new SimpleAuthenticationInfo(username,pwd,this.getName());
        return authc;


    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String username = (String) principalCollection.getPrimaryPrincipal();
        User user = (User)new RedisUtil().unSerializseObj(jedis.lrange(username.getBytes(),0,0).get(0));
        List<String> roles = user.getRoles();
        List<String> powers = user.getPowers();
        SimpleAuthorizationInfo  authz = new SimpleAuthorizationInfo();
        authz.addRoles(roles);
        authz.addStringPermissions(powers);
        jedis.close();
        log.info("检验用户权限"+username);
        return authz;
    }


}
